package cn.xiuxius.askbox.controller.common;

import cn.xiuxius.askbox.common.exception.FileNullException;
import cn.xiuxius.askbox.common.exception.FileTypeException;
import cn.xiuxius.askbox.common.utils.MinioUtil;
import cn.xiuxius.askbox.pojo.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

@RestController
@RequestMapping("/commons/upload")
@Api(tags = "通用-上传接口")
public class UploadController {

    @Autowired
    private MinioUtil minioUtil;

    @ApiOperation("上传图片")
    @PostMapping("/image")
    public Result uploadImage(MultipartFile file) throws Exception {
        if (file == null) {
            throw new FileNullException("图片不能为空");
        }

        String contentType = file.getContentType();
        if (contentType == null || !contentType.startsWith("image")) {
            throw new FileTypeException("请上传图片");
        }
        String originalFilename = file.getOriginalFilename();
        String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
        String url = minioUtil.upload(file.getInputStream(), extName);
        return Result.success(url);
    }

}
